# -*- coding: utf-8 -*-
import sqlite3
import re
from Bauteilkiste.Modules import Settings

class Datenbank():
    tableValues = {}
    
    def __init__(self, db = "databases/data.sqlite"):
        self.connection = sqlite3.connect(db)
        self.cursor = self.connection.cursor()
        
    def loadDB(self, table):
        #for table in tables:
        try:
            self.cursor.execute('SELECT * FROM "'+table+'"')
            self.tableValues[table] = self.cursor.fetchall()
        except:
            print ("DB Fehler beim Datenbank laden: "+table)
            s = Settings.Settings()
            createSQL = 'CREATE TABLE "main"."'+table+'" (' 
            for tableDesc in s.settings["tables"]:
                if tableDesc[0] == table:
                    for l in tableDesc[1]:
                        createSQL += '"'+l+'" '+tableDesc[3][l]+','
                    break
            createSQL = re.sub("\,\Z", "", createSQL)
            createSQL += ")"
            self.cursor.execute(createSQL)
            self.connection.commit()
            self.loadDB(table)
    #            if table[0] == u"Widerstände":
    #                print "Widerstände erstellt"
    #                self.cursor.execute('CREATE  TABLE "main"."Widerstände" ("UID" INTEGER PRIMARY KEY  NOT NULL  UNIQUE , "Wert" INTEGER, "Einheit" TEXT DEFAULT Ohm, "Material" TEXT, "Leistung" REAL, "Bauform" TEXT, "Menge" INTEGER, "Preis" REAL, "Reichelt" TEXT, "Notizen" TEXT)')
    #            elif table[0] == "Dioden":
    #                print "Dioden erstellt"
    #                self.cursor.execute('CREATE  TABLE "main"."Dioden" ("UID" INTEGER PRIMARY KEY  NOT NULL  UNIQUE , "Bezeichnung" TEXT, "Typ" TEXT, "Spannung" REAL, "Stromstärke" TEXT, "Bauform" TEXT, "Menge" INTEGER DEFAULT 0, "Preis" REAL, "Reichelt" TEXT, "Notizen" TEXT)')
    #            else:
    #                print "keine passenden Tabelleninfos für "+table[0]
    
    def __del__(self):
        self.connection.commit()
        self.connection.close()